const {
  app,
  BrowserWindow,
  ipcMain,
  screen,
  Menu,
  globalShortcut
} = require('electron')
const {exec} = require('child_process')
const { enable } = require('@/common/winUtils/enable')
const path = require('path')
let ico, preload
if (process.env.ENV == 'development') {
  ico = path.join(process.cwd(), './resources/logo.ico')
  preload = path.join(process.cwd(), './resources/app/preload.js')
} else {
  ico = path.join(__dirname, '../logo.ico')
  preload = path.join(__dirname, '../app/preload.js')
}
let win = null
const checkWin = {
  createWin: (secret) => {
    if (win) {
      win.show()
      return false
    }
    // var workAreaSize = screen.getPrimaryDisplay().workAreaSize;
    win = new BrowserWindow({
      width: 350,
      height: 350,
      title: '结账',
      resizable: false,
      maximizable: false,
      frame: false,
      show: true,//是否显示界面 先设置否
      icon: ico,
      webPreferences: {
        partition: String(+new Date()),
        plugins: true, //是否支持插件
        nodeIntegration: true,
        contextIsolation: false,
        webViewTag: true,
        webSecurity: false,
        enableRemoteModule: true
      }
    })
    win.setMenu(null)
    globalShortcut.register('CommandOrControl+Shift+d', function () {
      win.webContents.openDevTools()
    })
    // 指定一个入口的html文件
    let loadFailureCount = 0;
    win.loadURL(process.env.VUE_APP_WEB_DOMAIN + '/check?secret=' + encodeURIComponent(secret))
    win.webContents.on('did-fail-load', (event, errorCode) => {
      console.log('网页加载异常。。。'+errorCode)
      loadFailureCount++;
      if (loadFailureCount <= 3) {
        setTimeout(() => {
          win.loadURL(process.env.VUE_APP_WEB_DOMAIN + '/check?secret=' + encodeURIComponent(secret))
        }, 500)
      }
    })
    win.webContents.on('did-finish-load', () => {
      loadFailureCount = 0;
    });
    enable(win)
    win.on('closed', () => {
      win = null
    })
    win.once('ready-to-show', () => {
      win.show()
    })
    ipcMain.on('window-check-min', (event, obj) => {
      if(win) win.hide()
    })
    ipcMain.on('window-check-close', (event, obj) => {
      if(win) win.close()
    })
    ipcMain.on('member-deplane', (event, obj) => {
      win.webContents.send('member-deplane', secret)
    })
    ipcMain.on('window-all-closed', function (event,shutdown = false) {
      if (shutdown) {
        exec('shutdown -s -t 0')
      }
      checkWin.quit()
      app.exit()
    })
  },
  quit: () => {
    if(win) win.close()
  }
}
module.exports = checkWin
